package com.oa.meet.ctrl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.mdp.core.entity.LangTips;
import com.mdp.core.entity.Result;
import com.mdp.core.entity.Tips;
import com.mdp.core.query.QueryTools;
import com.mdp.core.utils.RequestUtils;
import com.mdp.safe.client.entity.User;
import com.mdp.safe.client.utils.LoginUtils;
import com.mdp.swagger.ApiEntityParams;
import com.oa.meet.entity.MeetMeeting;
import com.oa.meet.entity.MeetMeetingVo;
import com.oa.meet.service.MeetMeetingExecService;
import com.oa.meet.service.MeetMeetingService;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import io.swagger.annotations.ApiResponse;
import io.swagger.annotations.ApiResponses;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.*;
import springfox.documentation.annotations.ApiIgnore;

import java.text.SimpleDateFormat;
import java.util.*;
import java.util.stream.Collectors;

/**
 * @author maimeng-mdp code-gen
 * @since 2023年10月9日
 */
@RestController
@RequestMapping(value = "/**/oa/meet/meetMeeting")
@Api(tags = {"会议表-操作接口"})
public class MeetMeetingController {

    static Logger logger = LoggerFactory.getLogger(MeetMeetingController.class);
    @Autowired
    private MeetMeetingService meetMeetingService;
    @Autowired
    MeetMeetingExecService meetMeetingExecService;

    @RequestMapping(value = "/checkMeetingTime", method = RequestMethod.GET)
    public Result checkMeetingTime(@RequestParam Map<String, Object> meetMeeting) {
        Tips tips = new Tips("查询成功，无冲突");
        QueryWrapper<MeetMeeting> qw = QueryTools.initQueryWrapper(MeetMeeting.class, meetMeeting);
        IPage page = QueryTools.initPage(meetMeeting);

        //利用meetMeeting的id和roomId查出execDates
        if (StringUtils.hasText((String) meetMeeting.get("roomId"))) {
            List<String> exeDates = new ArrayList<>();
            Map<String, Object> thisMeeting = new HashMap<>();
            thisMeeting.put("id", meetMeeting.get("id"));
            thisMeeting.put("roomId", meetMeeting.get("roomId"));
            List<Map<String, Object>> thisMeets = meetMeetingService.selectListMapByWhere(page, qw, thisMeeting);
            for (Map<String, Object> thisMeet : thisMeets) {
                exeDates.add((String) thisMeet.get("execDate"));
            }
            //根据会议日期、会议室id列出同一天的MeetMeeting列表，然后遍历会议列表，看是否冲突
            for (String exeDate : exeDates) {
                Map<String, Object> queryMeeting = new HashMap();
                queryMeeting.put("execDate", exeDate);
                queryMeeting.put("roomId", meetMeeting.get("roomId"));
                queryMeeting.put("noMeetingId", meetMeeting.get("id"));
                List<Map<String, Object>> meetMeetingList = meetMeetingService.selectListMapByWhere(null, null, queryMeeting);
                //遍历当天会议，startTime>所有的EndTime||endTime<所有的startTime不冲突，否则冲突
                String newStartTime = (String) meetMeeting.get("startTime");
                String newEndTime = (String) meetMeeting.get("endTime");
                for (Map<String, Object> thisDayMeeting : meetMeetingList) {
                    if (newStartTime.compareTo((String) thisDayMeeting.get("endTime")) >= 0 || newEndTime.compareTo((String) thisDayMeeting.get("startTime")) <= 0) {
                        //doNothing
                    } else {
                        String msg = "" + thisDayMeeting.get("roomName") + "使用冲突";
                        return Result.ok(msg);
                    }
                }
            }
        }
        return Result.ok().setData(tips);
    }

    @ApiOperation(value = "会议表-查询列表", notes = " ")
    @ApiEntityParams(MeetMeeting.class)
    @ApiResponses({@ApiResponse(code = 200, response = MeetMeeting.class, message = "{tips:{isOk:true/false,msg:'成功/失败原因',tipscode:'错误码'},total:总记录数,data:[数据对象1,数据对象2,...]}")})
    @RequestMapping(value = "/list", method = RequestMethod.GET)
    public Result listMeetMeeting(@ApiIgnore @RequestParam Map<String, Object> params) {
        User user = LoginUtils.getCurrentUserInfo();
        RequestUtils.transformArray(params, "ids");
        QueryWrapper<MeetMeeting> qw = QueryTools.initQueryWrapper(MeetMeeting.class, params);
        IPage page = QueryTools.initPage(params);

        List<Map<String, Object>> datas = meetMeetingService.selectListMapByWhere(page, qw, params);
        return Result.ok("query-ok", "查询成功").setData(datas).setTotal(page.getTotal());
    }

    /**
     * 查询我的会议
     */
    @ApiOperation(value = "查询会议表信息列表", notes = " ")
    @ApiResponses({@ApiResponse(code = 200, response = MeetMeeting.class, message = "{tips:{isOk:true/false,msg:'成功/失败原因',tipscode:'错误码'},total:总记录数,data:[数据对象1,数据对象2,...]}")})
    @RequestMapping(value = "/minelist", method = RequestMethod.GET)
    public Result minelistMeetMeeting(@RequestParam Map<String, Object> meetMeeting) {
        RequestUtils.transformArray(meetMeeting, "ids");
        Map<String, Object> meetMeetingDb = new HashMap<>();
        Date date = new Date();
        SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy-MM-dd");
        String format = simpleDateFormat.format(date);
        meetMeetingDb.put("execDate", format);
        User user = LoginUtils.getCurrentUserInfo();
        meetMeetingDb.put("userid", user.getUserid());
        meetMeetingDb.put("orderBy", "exec_calc_date desc");
        QueryWrapper<MeetMeeting> qw = QueryTools.initQueryWrapper(MeetMeeting.class, meetMeeting);
        IPage page = QueryTools.initPage(meetMeeting);
//        PageUtils.startPage(meetMeetingDb);
        List<Map<String, Object>> meetMeetingList = meetMeetingService.selectMyMeetMeetingListMapByWhere(meetMeetingDb);    //列出MeetMeeting列表
//        PageUtils.responePage(m, meetMeetingList);

        return Result.ok("query-ok", "查询成功").setData(meetMeetingList);
    }

    /**
     * 管理会议
     */
    @ApiOperation(value = "查询会议表信息列表", notes = " ")
    @ApiResponses({@ApiResponse(code = 200, response = MeetMeeting.class, message = "{tips:{isOk:true/false,msg:'成功/失败原因',tipscode:'错误码'},total:总记录数,data:[数据对象1,数据对象2,...]}")})
    @RequestMapping(value = "/listAdministrator", method = RequestMethod.GET)
    public Result listAllMeetMeeting(@RequestParam Map<String, Object> meetMeeting) {
        RequestUtils.transformArray(meetMeeting, "ids");
        QueryWrapper<MeetMeeting> qw = QueryTools.initQueryWrapper(MeetMeeting.class, meetMeeting);
        IPage page = QueryTools.initPage(meetMeeting);
        // xml：res.status!="5"
        meetMeeting.putIfAbsent("status", 5);
        if (meetMeeting.containsKey("status")) {
            meetMeeting.put("status", 5);
        }
//        List<Map<String, Object>> meetMeetingList = meetMeetingService.selectAdminiMeetMeetingListMapByWhere(meetMeeting);    //列出
        List<Map<String, Object>> meetMeetingList = meetMeetingService.selectAdminiMeetMeetingListMapByWhere(page, qw, meetMeeting);    //列出

        return Result.ok().setData(meetMeetingList).setTotal(page.getTotal());
    }

    @ApiOperation(value = "查询会议表信息列表", notes = " ")
    @ApiResponses({@ApiResponse(code = 200, response = MeetMeeting.class, message = "{tips:{isOk:true/false,msg:'成功/失败原因',tipscode:'错误码'},total:总记录数,data:[数据对象1,数据对象2,...]}")})
    @RequestMapping(value = "/listMem", method = RequestMethod.GET)
    public Result listMemMeetMeeting(@RequestParam Map<String, Object> meetMeeting) {
        RequestUtils.transformArray(meetMeeting, "ids");
        QueryWrapper<MeetMeeting> qw = QueryTools.initQueryWrapper(MeetMeeting.class, meetMeeting);
        IPage page = QueryTools.initPage(meetMeeting);
//        PageUtils.startPage(meetMeeting);
//        List<Map<String, Object>> meetMeetingList = meetMeetingService.selectListByWhere(meetMeeting);
        List<Map<String, Object>> meetMeetingList = meetMeetingService.selectListMapByWhere(page, qw, meetMeeting);
//        PageUtils.responePage(m, meetMeetingList);

        return Result.ok().setData(meetMeetingList);
    }

    @ApiOperation(value = "会议表-新增", notes = " ")
    @ApiResponses({@ApiResponse(code = 200, response = MeetMeeting.class, message = "{tips:{isOk:true/false,msg:'成功/失败原因',tipscode:'失败时错误码'},data:数据对象}")})
    @RequestMapping(value = "/add", method = RequestMethod.POST)
    public Result addMeetMeeting(@RequestBody MeetMeetingVo meetMeetingVo) {


        meetMeetingVo = meetMeetingService.saveMeeting(meetMeetingVo);

        return Result.ok("add-ok", "添加成功！").setData(meetMeetingVo);
    }

    @ApiOperation(value = "会议表-删除", notes = " ")
    @ApiResponses({@ApiResponse(code = 200, message = "{tips:{isOk:true/false,msg:'成功/失败原因',tipscode:'失败时错误码'}}")})
    @RequestMapping(value = "/del", method = RequestMethod.POST)
    public Result delMeetMeeting(@RequestBody MeetMeeting meetMeeting) {


        if (StringUtils.isEmpty(meetMeeting.getId())) {
            return Result.error("id不能为空");
        }
        User user = LoginUtils.getCurrentUserInfo();
        if (!user.getUserid().equals(meetMeeting.getRequireUserid())) {
            return Result.error("只有申请人可以删除会议");
        }
        MeetMeeting meetMeetingDB = new MeetMeeting();
        meetMeetingDB.setId(meetMeeting.getId());
        meetMeetingDB.setStatus("5");
        meetMeetingDB.setCircleable("0");
        meetMeetingService.updateSomeFieldByPk(meetMeetingDB);
//            MeetMeetingExec meetMeetingExec = new MeetMeetingExec();
//            meetMeetingExec.setMeetingId(meetMeeting.getId());
//            List<Map<String,Object>> meetMeetingExecList = meetMeetingExecService.selectList("meetMeetSelectList", meetMeetingExec);
        meetMeetingService.allDelete(meetMeeting);

        return Result.ok("del-ok", "删除成功！");
    }

    @ApiOperation(value = "会议表-修改", notes = " ")
    @ApiResponses({@ApiResponse(code = 200, response = MeetMeeting.class, message = "{tips:{isOk:true/false,msg:'成功/失败原因',tipscode:'失败时错误码'},data:数据对象}")})
    @RequestMapping(value = "/edit", method = RequestMethod.POST)
    public Result editMeetMeeting(@RequestBody MeetMeetingVo meetMeetingVo) {


        meetMeetingVo = meetMeetingService.updateMeeting(meetMeetingVo);

        return Result.ok("edit-ok", "修改成功！").setData(meetMeetingVo);
    }

    @ApiOperation(value = "会议表-批量修改某些字段", notes = "")
    @ApiEntityParams(value = MeetMeeting.class, props = {}, remark = "会议表", paramType = "body")
    @ApiResponses({@ApiResponse(code = 200, response = MeetMeeting.class, message = "{tips:{isOk:true/false,msg:'成功/失败原因',tipscode:'失败时错误码'},data:数据对象}")})
    @RequestMapping(value = "/editSomeFields", method = RequestMethod.POST)
    public Result editSomeFields(@ApiIgnore @RequestBody Map<String, Object> params) {
        User user = LoginUtils.getCurrentUserInfo();
        meetMeetingService.editSomeFields(params);
        return Result.ok("edit-ok", "更新成功");
    }

    @ApiOperation(value = "会议表-批量删除", notes = " ")
    @ApiResponses({@ApiResponse(code = 200, message = "{tips:{isOk:true/false,msg:'成功/失败原因',tipscode:'失败时错误码'}")})
    @RequestMapping(value = "/batchDel", method = RequestMethod.POST)
    public Result batchDelMeetMeeting(@RequestBody List<MeetMeeting> meetMeetings) {
        User user = LoginUtils.getCurrentUserInfo();
        if (meetMeetings.size() <= 0) {
            return Result.error("batchDel-data-err-0", "请上送待删除数据列表");
        }
        List<MeetMeeting> datasDb = meetMeetingService.listByIds(meetMeetings.stream().map(i -> i.getId()).collect(Collectors.toList()));

        List<MeetMeeting> can = new ArrayList<>();
        List<MeetMeeting> no = new ArrayList<>();
        for (MeetMeeting data : datasDb) {
            if (true) {
                can.add(data);
            } else {
                no.add(data);
            }
        }
        List<String> msgs = new ArrayList<>();
        if (can.size() > 0) {
            meetMeetingService.removeByIds(can);
            msgs.add(LangTips.transMsg("del-ok-num", "成功删除%s条数据.", can.size()));
        }

        if (no.size() > 0) {
            msgs.add(LangTips.transMsg("not-allow-del-num", "以下%s条数据不能删除:【%s】", no.size(), no.stream().map(i -> i.getId()).collect(Collectors.joining(","))));
        }
        if (can.size() > 0) {
            return Result.ok(msgs.stream().collect(Collectors.joining()));
        } else {
            return Result.error(msgs.stream().collect(Collectors.joining()));
        }
    }

    @ApiOperation(value = "会议表-根据主键查询一条数据", notes = " ")
    @ApiResponses({@ApiResponse(code = 200, response = MeetMeeting.class, message = "{tips:{isOk:true/false,msg:'成功/失败原因',tipscode:'失败时错误码'},data:数据对象}")})
    @RequestMapping(value = "/queryById", method = RequestMethod.GET)
    public Result queryById(MeetMeeting meetMeeting) {
        MeetMeeting data = (MeetMeeting) meetMeetingService.getById(meetMeeting);
        return Result.ok().setData(data);
    }

}
